﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using cnFederal.FaCode;

namespace cnFederal.Admin
{
    public partial class EditSelectedFaNews : System.Web.UI.Page
    {
        FaPost _fapost;
        List<CnfiUser> _cnfiUsers;
        CultureInfo _ci;
        string _imageUrl;
        public EditSelectedFaNews()
        {
           _ci = new CultureInfo("nb-NO");
           CnfiUsers.Load();
           CnfImages.Load();
           FaPosts.Load(true);
           _cnfiUsers = CnfiUsers.GetAllUsers();
           
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            CnfImages.Load();
            int id = -1;
            string query = Request.QueryString["Id"];
            if (string.IsNullOrWhiteSpace(query))
                txtRegDate.Text = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;
            if (!IsPostBack)
                InitializeListbox();
            if (!string.IsNullOrWhiteSpace(query))
            {
                
                try
                {
                  id=  int.Parse(query);
                }
                catch (Exception ex) { }
                if(id != -1)
                Load(id);

            }
            if (Session["ImageUrl"] != null)
                this._imageUrl = Session["ImageUrl"].ToString();
            this.txtContent.Focus();
            MainTable.Visible = UserIdentity.Autenticated;
            
               
        }
        public string ImageUrl
        {
            get { return _imageUrl; }
            set { _imageUrl = value; }
        }

        public void Load(int id)
        {
            _fapost = FaPosts.GetFaPostById(id);
            if (!IsPostBack && _fapost != null)
            {
                DropDownListAuthor.SelectedValue =Convert.ToString( _fapost.AuthorId);
                DropDownListCategory.SelectedValue = _fapost.Category;
                DropDownListType.SelectedValue = _fapost.NewsType.ToString();
                txtRegDate.Text = _fapost.DateRegistered.Year + "-" + _fapost.DateRegistered.Month + "-" + _fapost.DateRegistered.Day;
                txtTitle.Text = _fapost.Title;
                txtDateStartPublish.Text = _fapost.DateStartPublish.Year + "-" + _fapost.DateStartPublish.Month + "-" + _fapost.DateStartPublish.Day;
                txtEndPublish.Text = _fapost.DateEndPublish.Year + "-" + _fapost.DateEndPublish.Month + "-" + _fapost.DateEndPublish.Day;
                txtHeader.Text = _fapost.Header;
                txtContent.Text = _fapost.MainContent;
                if (_fapost.Display == true)
                    RadioButtonEnable.Checked = true;
                else
                    RadioButtonDisable.Checked = true;
                imageSelected.ImageUrl = _fapost.ImageUrl;
                this.ImageUrl = _fapost.ImageUrl;
            }
        }
        protected void txtRegDate_TextChanged(object sender, EventArgs e)
        {

         

        }

        protected void txtDateStartPublish_TextChanged(object sender, EventArgs e)
        {
            //_fapost.DateStartPublish = DateTime.Parse(txtDateStartPublish.Text);


        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                int itemId = 0;
                if (_fapost == null)
                   itemId =  CreateNew();
                else
                    Update();
                string id = Request.QueryString["Id"];
                if (!string.IsNullOrWhiteSpace(id))
                {
                    if (itemId == 0)
                    itemId = Convert.ToInt32(id);
                    if (_image != null)
                    {
                        _image.LinkId = itemId;
                        _image.LinkType = (int)SysObjects.POST;
                        CnfImages.Save(_image);
                    }
                }
              
                Response.Redirect(AbsoluteURI);

            }
            catch (Exception ex)
            {
                //Nothing to do. 
            }

        }

        public string RootDomain
        {
            get
            {
                return HttpContext.Current.Request.Url.Authority;
            }
        }
        public string AbsoluteURI
        {
            get
            {
                return HttpContext.Current.Request.Url.AbsoluteUri;
            }
        }
        private void Update()
        {
             if(!string.IsNullOrWhiteSpace(DropDownListAuthor.SelectedValue))
                 _fapost.AuthorId =  Convert.ToInt32(DropDownListAuthor.SelectedValue);
            _fapost.Category = DropDownListCategory.SelectedValue;
            if(!string.IsNullOrWhiteSpace(DropDownListType.SelectedValue))
                _fapost.NewsType = Convert.ToInt32(DropDownListType.SelectedValue);
            _fapost.DateEndPublish = DateTime.Parse(txtEndPublish.Text, _ci);
            _fapost.DateStartPublish = DateTime.Parse(txtDateStartPublish.Text, _ci);
            _fapost.DateUpdated = DateTime.Now;
            _fapost.Header =   txtHeader.Text;
            if(!string.IsNullOrWhiteSpace(this.ImageUrl))
            _fapost.ImageUrl = this.ImageUrl;
            _fapost.MainContent = txtContent.Text;
            _fapost.Title = txtTitle.Text;
            if(RadioButtonEnable.Checked)
            _fapost.Display = true;
            else
                _fapost.Display = false;
            FaPosts.Save(_fapost);
        }

        private int CreateNew()
        {
            
            _fapost = new FaPost();
            _fapost.AuthorId = this._AuthorId;
            _fapost.Category = this._category;
            _fapost.NewsType = Convert.ToInt32(_newsType);
            _fapost.DateEndPublish = DateTime.Parse(txtEndPublish.Text, _ci);
            _fapost.DateRegistered = DateTime.Now;
            _fapost.DateStartPublish = DateTime.Parse(txtDateStartPublish.Text, _ci);
            _fapost.DateUpdated = DateTime.Now;
            _fapost.Header = txtHeader.Text;
            _fapost.ImageUrl = this.ImageUrl;
            _fapost.MainContent = txtContent.Text;
            _fapost.Title = txtTitle.Text;
            if (RadioButtonEnable.Checked)
                _fapost.Display = true;
            else
                _fapost.Display = false;
           return FaPosts.CreateNew(_fapost);


        }

        protected void btnBrows_Click(object sender, EventArgs e)
        {
             UploadImage();
            //Response.Redirect(Request.RawUrl);
             
        }

      
        CnfImage _image;
        private void UploadImage()
        {
            string msg = "";
            if (fileupload1.HasFile)
            {
                try
                {
                    string[] sTypes = { "image/jpg", "image/jpeg", "image/pjpeg", "image/gif", "image/x-png", "image/png" };
                    bool bIsMatch = false;
                    foreach (string sType in sTypes)
                    {
                        if (String.Compare(sType, fileupload1.PostedFile.ContentType, true) == 0)
                            bIsMatch = true;
                    }

                    if (bIsMatch)
                    {
                        if (fileupload1.PostedFile.ContentLength < 1002400)
                        {
                           // string appPath = Request.PhysicalApplicationPath;
                           
                            string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
                            //fileupload1.SaveAs(Server.MapPath(Path.Combine("~/Images/", filename)));
                           _image = CnfImages.GetImageByName(fileupload1.FileName);
                            if (_image == null)
                            {
                                CnfImage img = new CnfImage();
                                img.Image = fileupload1.FileBytes;
                                img.ImageName = fileupload1.FileName;
                                if(_fapost != null)
                                img.LinkId = _fapost.Id;
                                img.LinkType = (int)SysObjects.POST;
                                CnfImages.CreateNew(img);
                                _image = CnfImages.GetLastAddedImage();
                                
                            }
                            this._imageUrl = "http://"+RootDomain +"/ImgHandler.ashx?id=" + _image.Id;
                            Session["ImageUrl"] = this._imageUrl;
                            this.imageSelected.ImageUrl = this._imageUrl;

                        }
                        else
                            msg = "Upload status: The file has to be less than 1 MB!";
                    }
                    else
                        msg = "Upload status: Only JPEG files are accepted!";
                }
                catch (Exception ex)
                {
                    msg = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }

        }

        private void InitializeListbox()
        {
            
            if (_cnfiUsers != null && _cnfiUsers.Count != 0)
            {

                foreach (CnfiUser u in _cnfiUsers)
                {
                    ListItem item = new ListItem(u.Name, u.Id.ToString());
                    DropDownListAuthor.Items.Add(item);
                }
                ListItem nullItem = new ListItem("", "");
                nullItem.Selected = true;
                DropDownListAuthor.Items.Add(nullItem);
               
            }

        }
        private string _category;
        private int _AuthorId;
        protected void DropDownListAuthor_SelectedIndexChanged(object sender, EventArgs e)
        {
            _AuthorId = Convert.ToInt32(DropDownListAuthor.SelectedValue);
        }

        protected void DropDownListCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            _category = DropDownListCategory.SelectedItem.Text;
        }

        private bool _display;
        protected void RadioButtonEnable_CheckedChanged(object sender, EventArgs e)
        {
            Session["display"] = true;
        }

        protected void RadioButtonDisable_CheckedChanged(object sender, EventArgs e)
        {
            Session["display"] = false;
        }

        string _newsType = null;
        protected void DropDownListType_SelectedIndexChanged(object sender, EventArgs e)
        {
            _newsType = DropDownListType.SelectedValue;
        }

      
       


    }
}